package com.baiyun.crm.workbench.web.controller;

import com.baiyun.crm.commons.constant.Constants;
import com.baiyun.crm.commons.domain.ReturnObject;
import com.baiyun.crm.commons.utils.DateUtils;
import com.baiyun.crm.commons.utils.HSSFUtils;
import com.baiyun.crm.commons.utils.UUIDUtils;
import com.baiyun.crm.settings.domain.User;
import com.baiyun.crm.settings.service.UserService;
import com.baiyun.crm.workbench.domain.Activity;
import com.baiyun.crm.workbench.domain.ActivityRemark;
import com.baiyun.crm.workbench.service.ActivityRemarkService;
import com.baiyun.crm.workbench.service.ActivityService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Controller
public class ActivityController {

    @Autowired
    private UserService userService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivityRemarkService ActivityRemarkService;

    @RequestMapping("/workbench/activity/index.do")
    public String index(HttpServletRequest request){
        //调用service方法，查询所有用户
        List<User> userList = userService.querAllUsers();
        //把数据保存到request中
        request.setAttribute("userList",userList);
        return "workbench/activity/index";
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/saveCreateActivity.do")
    public Object saveCreateActivity(Activity activity, HttpSession session){
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        //封装参数
        activity.setId(UUIDUtils.getUUID());
        activity.setCreateTime(DateUtils.formateDateTime(new Date()));
        activity.setCreateBy(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service
            int ret = activityService.saveCreateActivity(activity);
            if (ret>0){
                returnObject.setCode(Constants.CODE_SUCCESS);
            }else {
                returnObject.setCode(Constants.CODE_FAIL);
                returnObject.setMessage("系统繁忙，请重试...");
            }
        }catch (Exception e){
            e.printStackTrace();
            returnObject.setCode(Constants.CODE_FAIL);
            returnObject.setMessage("系统繁忙，请重试...");
        }
        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/querActivityByConditionForPage.do")
    public Object querActivityByConditionForPage(String name,String owner,String startDate,String endDate,
                                                 int pageNo,int pageSize){
        //封装参数
        Map<String,Object> map = new HashMap<>();
        map.put("name",name);
        map.put("owner",owner);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("beginNo",(pageNo-1)*pageSize);
        map.put("pageSize",pageSize);
        //调用service方法，查询数据
        List<Activity> activityList = activityService.querActivityByConditionForPage(map);
        int totalRows = activityService.querCountOfActivityByCondition(map);
        //根据查询结果。生成响应信息
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("activityList",activityList);
        retMap.put("totalRows",totalRows);
        return retMap;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/deleteActivityIds.do")
    public Object deleteActivityIds(String[] id){
        ReturnObject returnObject = new ReturnObject();
        try{
            //调用service，删除市场活动
            int ret = activityService.deleteActivityByIds(id);
            if (ret>0){
                returnObject.setCode(Constants.CODE_SUCCESS);
            }else {
                returnObject.setCode(Constants.CODE_FAIL);
                returnObject.setMessage("系统繁忙，请重试...");
            }
        }catch (Exception e){
            e.printStackTrace();
            returnObject.setCode(Constants.CODE_FAIL);
            returnObject.setMessage("系统繁忙，请重试...");
        }
        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/queryActivityById.do")
    public Object queryActivityById(String id){
        //调用service方法，查询市场活动
        Activity activity = activityService.queryActivityById(id);
        //根据查询结果，返回响应信息
        return activity;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/saveEditActivity.do")
    public Object saveEditActivity(Activity activity,HttpSession session){
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        //进一步封装参数
        activity.setEditTime(DateUtils.formateDateTime(new Date()));
        activity.setEditBy(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            int ret = activityService.saveEditActivity(activity);
            if (ret>0){
                returnObject.setCode(Constants.CODE_SUCCESS);
            }else {
                returnObject.setCode(Constants.CODE_FAIL);
                returnObject.setMessage("系统繁忙，请重试...");
            }
        }catch (Exception e){
            e.printStackTrace();
            returnObject.setCode(Constants.CODE_FAIL);
            returnObject.setMessage("系统繁忙，请重试...");
        }
        return returnObject;

    }

    @RequestMapping("/workbench/activity/exportAllActivitys.do")
    public void exportAllActivitys(HttpServletResponse response) throws Exception{
        //调用servuce方法，查询所有市场活动信息
        List<Activity> activityList = activityService.queryAllActivitys();
        //创建exel文件，并把activityList写入
        HSSFWorkbook wb = new HSSFWorkbook();
        //页
        HSSFSheet sheet = wb.createSheet("市场活动列表");

        //这是第一行
        HSSFRow row = sheet.createRow(0);
        //这是第一行里面的第n列
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellValue("所有者");
        cell = row.createCell(2);
        cell.setCellValue("名称");
        cell = row.createCell(3);
        cell.setCellValue("开始日期");
        cell = row.createCell(4);
        cell.setCellValue("结束日期");
        cell = row.createCell(5);
        cell.setCellValue("成本");
        cell = row.createCell(6);
        cell.setCellValue("描述");
        cell = row.createCell(7);
        cell.setCellValue("创建时间");
        cell = row.createCell(8);
        cell.setCellValue("创建者");
        cell = row.createCell(9);
        cell.setCellValue("修改时间");
        cell = row.createCell(10);
        cell.setCellValue("修改者");

        //遍历activityList，创建HSSFRow对象，生成所有的数据行
        if (activityList!=null && activityList.size()>0){
            Activity activity = null;
            for (int i=0;i< activityList.size();i++){
                activity = activityList.get(i);
                //每遍历出市场活动对象，生成一行
                row = sheet.createRow(i+1);
                //每一行创建11列
                cell = row.createCell(0);
                cell.setCellValue(activity.getId());
                cell = row.createCell(1);
                cell.setCellValue(activity.getOwner());
                cell = row.createCell(2);
                cell.setCellValue(activity.getName());
                cell = row.createCell(3);
                cell.setCellValue(activity.getStartDate());
                cell = row.createCell(4);
                cell.setCellValue(activity.getEndDate());
                cell = row.createCell(5);
                cell.setCellValue(activity.getCost());
                cell = row.createCell(6);
                cell.setCellValue(activity.getDescription());
                cell = row.createCell(7);
                cell.setCellValue(activity.getCreateTime());
                cell = row.createCell(8);
                cell.setCellValue(activity.getCreateBy());
                cell = row.createCell(9);
                cell.setCellValue(activity.getEditTime());
                cell = row.createCell(10);
                cell.setCellValue(activity.getEditBy());
            }
        }
        //根据wb对象生成excel文件
        /*OutputStream os = new FileOutputStream("C:\\Users\\20516\\Desktop\\SSM\\项目资料\\clientDir\\activityListTwo.xls");
        wb.write(os);
        //关闭资源*/
        /*os.close();
        wb.close();*/

        //把生成的文件下载到用户客户端
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.addHeader("Content-Disposition","attachment;filename=activityListTwo.xls");
        ServletOutputStream out = response.getOutputStream();
        /*InputStream is = new FileInputStream("C:\\Users\\20516\\Desktop\\SSM\\项目资料\\clientDir\\activityListTwo.xls");
        //设置缓冲区
        byte[] buff = new byte[256];
        int len=0;
        while ((len=is.read(buff)) != -1){
            out.write(buff,0,len);
        }
        is.close();*/
        wb.write(out);
        wb.close();
        out.flush();
    }

    @RequestMapping("/workbench/activity/exportTemplateActivitys.do")
    public void exportTemplateActivitys(HttpServletResponse response) throws Exception{
        //创建exel文件，并把activityList写入
        HSSFWorkbook wb = new HSSFWorkbook();
        //页
        HSSFSheet sheet = wb.createSheet("市场活动列表");

        //这是第一行
        HSSFRow row = sheet.createRow(0);
        //这是第一行里面的第n列
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("名称");
        cell = row.createCell(1);
        cell.setCellValue("开始日期");
        cell = row.createCell(2);
        cell.setCellValue("结束日期");
        cell = row.createCell(3);
        cell.setCellValue("成本");
        cell = row.createCell(4);
        cell.setCellValue("描述");

        //这是第二行
        row = sheet.createRow(1);
        //这是第一行里面的第n列
        cell = row.createCell(0);
        cell.setCellValue("test01");
        cell = row.createCell(1);
        cell.setCellValue("2020-10-26");
        cell = row.createCell(2);
        cell.setCellValue("2020-10-29");
        cell = row.createCell(3);
        cell.setCellValue("200");
        cell = row.createCell(4);
        cell.setCellValue("描述测试");

        //把生成的文件下载到用户客户端
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.addHeader("Content-Disposition","attachment;filename=activityListTemplate.xls");
        ServletOutputStream out = response.getOutputStream();
        wb.write(out);
        wb.close();
        out.flush();
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/importActivity.do")
    public Object importActivity(MultipartFile activityFile,HttpSession session){
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        ReturnObject returnObject = new ReturnObject();
        try {
            //把excel文件写到磁盘目录中
            //String originalFilename = activityFile.getOriginalFilename();
            //File file = new File("C:\\Users\\20516\\Desktop\\SSM\\项目资料\\serverDir\\", originalFilename);
            //activityFile.transferTo(file);

            //解析excel文件，获取文件中的数据，并且封装成activityList
            //InputStream is = new FileInputStream("C:\\Users\\20516\\Desktop\\SSM\\项目资料\\serverDir\\" + originalFilename);

            InputStream is = activityFile.getInputStream();
            HSSFWorkbook wb = new HSSFWorkbook(is);
            HSSFSheet sheet = wb.getSheetAt(0); //页的下标
            HSSFRow row = null;
            HSSFCell cell = null;
            Activity activity = null;
            List<Activity> activityList = new ArrayList<>();
            for (int i=1;i<=sheet.getLastRowNum();i++){ //sheet.getLastRowNum() 最后一行的下标
                row = sheet.getRow(i); //行的下标
                activity = new Activity();
                activity.setId(UUIDUtils.getUUID()); //市场活动id
                activity.setOwner(user.getId());    //所有者id
                activity.setCreateTime(DateUtils.formateDateTime(new Date())); //创建时间
                activity.setCreateBy(user.getId()); //创建者
                for (int j=0;j<row.getLastCellNum();j++){ //row.getLastCellNum() 最后一列的下标+1
                    cell = row.getCell(j);//列的下标
                    //调用工具类获取数据
                    String cellValue = HSSFUtils.getCellValueForStr(cell);
                    switch (j){
                        case 0:
                            activity.setName(cellValue);
                            break;
                        case 1:
                            activity.setStartDate(cellValue);
                            break;
                        case 2:
                            activity.setEndDate(cellValue);
                            break;
                        case 3:
                            activity.setCost(cellValue);
                            break;
                        case 4:
                            activity.setDescription(cellValue);
                            break;
                    }
                    /*if (j==0){
                        activity.setName(cellValue);
                    }else if (j==1){
                        activity.setStartDate(cellValue);
                    }else if (j==2){
                        activity.setEndDate(cellValue);
                    }else if (j==3){
                        activity.setCost(cellValue);
                    }else if (j==4){
                        activity.setDescription(cellValue);
                    }*/
                }
                //把所有的列都封装好之后，保存到list中
                activityList.add(activity);
            }
            //调用service方法，保存市场活动
            int ret = activityService.saveCreateActivityByList(activityList);

            returnObject.setCode(Constants.CODE_SUCCESS);
            returnObject.setRetData(ret);

        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constants.CODE_FAIL);
            returnObject.setMessage("系统繁忙，请重试...");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/activity/detailActivity.do")
    public String detailActivity(String id,HttpServletRequest request){
        //调用service方法，查询数据
        Activity activity = activityService.queryActivityForDetailById(id);
        List<ActivityRemark> remarkList = ActivityRemarkService.queryActivityRemarkForDetailByActivityId(id);
        //把数据保存到作用域中
        request.setAttribute("activity",activity);
        request.setAttribute("remarkList",remarkList);
        //请求转发
        return "workbench/activity/detail";
    }
}
